﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data;
using Data.implement;
using log4net;
using Services.Interface;
using Services.Implement;

namespace Services.Implement
{
    public class AuthService : IAuthService
    {
        private IUserRepositery userRepositery;
        private ILog Logger;
        public AuthService()
        {
            Logger = LogManager.GetLogger(this.GetType());
            userRepositery = DataRepositeryManagerFactory.CreateUserRepositery();
        }

        public User Login(int carType, WeiXinUser weiXinUser)
        {
            Logger.Info("Login begin.");
            User user;
            bool exist = IsExistNumber(weiXinUser,carType,out user);
            if (exist)
            {
                return user;
            }
            else
            {
                //返回错误信息用户名错误
                return null;
            }

        }

        private bool IsExistNumber(WeiXinUser weiXinUser, int carType,out User user)
        {
            try
            {
                user = userRepositery.GetOrInsertUser(weiXinUser, carType: carType);

                if (user.CarId == null)
                {
                    Logger.InfoFormat("User {0}-{1} do not have car.", user.UserId, user.nickname);
                    user = userRepositery.SetUserCar(user.UserId, carType);

                }
                return true;
            }
            catch (Exception e)
            {
                Logger.Error("AuthService-Login-IsExistNumber has an error:" + e + "./n/rThe user is " + weiXinUser.openId + " /n/r" + weiXinUser.nickname + " /n/r" + weiXinUser.sex + " /n/r" + weiXinUser.country + " /n/r" + weiXinUser.province + " /n/r" + weiXinUser.city + " /n/r" + weiXinUser.headimgurl);
                throw;
            }
            
        }
    }

    

   
}
